<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Welcome extends Controller {

	public function action_gallery_page() {
		
		if( isset($_FILES['uploaded-image']) ) {
		
			$image_name = $_FILES['uploaded-image']['name'];
			
			if( preg_match('/(.+)\.(jpe?g|png)\Z/i', $image_name, $m) ) {
				
				$pref = 1;
				
				$p = "upload/$image_name";
				
				while( file_exists($p) ) {
					$pref++;
					$nm = $m[1].'_'.$pref.'.'.$m[2];
					 $p = "upload/$nm";
				}
				
				$image_name = isset($nm) ? $nm : $image_name ;
				
				move_uploaded_file($_FILES['uploaded-image']['tmp_name'], $p);
				
				$image = Image::factory($p);
				
				$proportion = $image->width/$image->height;
				
				$bool = false;
			
				if( $image->width > $image->height ) {
					if( $image->width > 150 ) {
						$new_width = 150;
						$new_height = intval($new_width/$proportion);
						$bool = true;
					}
				} else {
					if( $image->height > 150 ) {
						$new_height = 150;
						$new_width = $new_height*$proportion;
						$bool = true;
					}
				}
				
				if( $bool ) {
					$image->resize($new_width, $new_height);
					$image->save("upload/thumb/$image_name");
				} else {
					copy("upload/$image_name", "upload/thumb/$image_name");
				}
				
				$des = addslashes($_POST['des']);
				$post_date = time();
			
				$sql = "INSERT INTO kohana_gallery 
							 VALUES ('$des', '$image_name', $post_date)";
				
				DB::query(Database::INSERT, $sql)->execute();
			}
		}
		
		if( isset($_POST['page']) ) {
		
			$sql = 'SELECT COUNT(*) 
					  FROM kohana_gallery';
			$record_0 = DB::query(Database::SELECT, $sql)->execute();
			
			$f = ($_POST['page']-1)*12;
			$sql = "SELECT des, image_name
					  FROM kohana_gallery
				  ORDER BY post_date
					 LIMIT $f,12";
			$record_1 = DB::query(Database::SELECT, $sql)->execute();
			
			$out = '';
			foreach( $record_1 as $record ) {
				$out .= $record['des'].'^'.$record['image_name'].'^';
			}
			$BODY = rtrim($record_0[0]['COUNT(*)'].'^'.$out, '^');
		} else {
			$BODY = View::factory('gallery_page');
		}
		
		$this->response->body($BODY);
	}
}